package im.starchat.chat.activity.account;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.util.SparseArrayCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.tencent.TIMManager;
import com.umeng.message.ALIAS_TYPE;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import java.util.HashMap;
import java.util.Stack;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import im.starchat.chat.R;
import im.starchat.chat.XLApplication;
import im.starchat.chat.activity.BaseActivity;
import im.starchat.chat.activity.Main2Activity;
import im.starchat.chat.activity.RecommendStarActivity;
import im.starchat.chat.rest.model.api.LoginResponse;
import im.starchat.chat.rest.model.api.NullResponse;
import im.starchat.chat.utils.Constants;
import im.starchat.chat.utils.GsonUtil;
import im.starchat.chat.utils.PreferencesStorageUtil;
import im.starchat.chat.utils.RetrofitErrorUtil;
import im.starchat.chat.utils.UserUtils;
import im.starchat.chat.utils.Util;
import im.starchat.chat.view.CycleViewPager;
import im.starchat.chat.view.MyViewPager;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    public static String TAG = "LoginActivity";


    @InjectView(R.id.weixin)
    ImageView mWeixin;
    @InjectView(R.id.weibo)
    ImageView mWeiBo;
    @InjectView(R.id.viewpager)
    CycleViewPager mCycleViewPager;
    @InjectView(R.id.icon_1)
    View icon_1;
    @InjectView(R.id.icon_2)
    View icon_2;
    @InjectView(R.id.icon_3)
    View icon_3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedata = getApplicationContext().getSharedPreferences(Constants.LOCAL_DATA, Context.MODE_APPEND);
        ShareSDK.initSDK(this);

        //如果已经登录了，直接跳过登录界面，否则显示登录界面
        if (PreferencesStorageUtil.isUserLogin(this)) {
            UserUtils.setUserInstance(PreferencesStorageUtil.getUserBean(this));

            TIMManager.getInstance().setEnv(Util.ENV_FORMAL);
            TIMManager.getInstance().init(getApplicationContext());
            toMainActivity();

        } else {
            setContentView(R.layout.login_activity);
            ButterKnife.inject(this);
            mWeixin.setOnClickListener(this);
            mWeiBo.setOnClickListener(this);
//            mShareAPI = UMShareAPI.get(this);
            initCyclePagerAdapter();
        }
    }

    private void initCyclePagerAdapter() {
        setPage(0);
        MyAdapter myAdapter = new MyAdapter();
        myAdapter.setRealCount(3);
        mCycleViewPager.setAbstractCircleAdapter(myAdapter);
        mCycleViewPager.setDelayTime(2000);
        mCycleViewPager.initPage(0);
        mCycleViewPager.setEnableCycle(true);
        mCycleViewPager.setOnPageChangeListener(new MyPageChangeListener());

    }

    private void setPage(int page) {
        if (page < 0) {
            page = 0;
        } else if (page > 2) {
            page = 2;
        }
        View[] icons = new View[]{icon_1, icon_2, icon_3};
        for (int i = 0; i < icons.length; i++) {
            boolean selected = i == page;
            icons[i].setSelected(selected);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.weixin:
                    loginWeixin();
                break;
            case R.id.weibo:
                    loginWeibo();
                break;

            default:
                break;
        }
    }

    private void loginWeibo() {
        showProgressDialog();

        Platform weibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);
        if(weibo.isClientValid()){
            weibo.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {
                    System.out.println("loginWeibo--authorize->onComplete");
                    dismissProgressDialog();
                    initWeboUser();
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {
                    dismissProgressDialog();
//                showFailureToast();
                }

                @Override
                public void onCancel(Platform platform, int i) {
                    dismissProgressDialog();
//                showFailureToast();
                }
            });
            weibo.authorize(new String[]{"follow_app_official_microblog"});
        }else{
            toast("没有安装微博客户端", Toast.LENGTH_SHORT);
        }

    }


    private void initWeboUser() {
        Platform weibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);
        weibo.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {
                showProgressDialog("正在登陆");
                PlatformDb platDB = platform.getDb();//获取数平台数据DB
                String sex = "male";
                if (!TextUtils.isEmpty(platDB.getUserGender()) ) {
                    if(platDB.getUserGender().equals("f")){
                        sex = "female";
                    }else{
                        sex = "male";
                    }
                }
                //通过DB获取各种数据
//                postSignup(, platDB.getToken(), stringObjectHashMap.get("name").toString(), stringObjectHashMap.get("profile_image_url").toString());
//                System.out.println("sex " + stringObjectHashMap.get("sex").toString());

                XLApplication.getInstance().getRestClient().signIn("weibo", stringObjectHashMap.get("id").toString(), platDB.getToken(), "",
                        "", stringObjectHashMap.get("profile_image_url").toString(), sex, stringObjectHashMap.get("city").toString(), stringObjectHashMap.get("screen_name").toString(), stringObjectHashMap.get("description").toString(), new Callback<LoginResponse>() {
                            @Override
                            public void success(LoginResponse loginResponse, Response response) {
                                UserUtils.setUserInstance(UserUtils.transLoginRes2User(loginResponse));
                                PreferencesStorageUtil.setUserBean(LoginActivity.this, GsonUtil.toJson(UserUtils.transLoginRes2User(loginResponse)));
                                PreferencesStorageUtil.setToken(LoginActivity.this, loginResponse.getAuthentication_token());
                                PreferencesStorageUtil.setUserid(LoginActivity.this, loginResponse.getId() + "");
                                PreferencesStorageUtil.setTsig(LoginActivity.this, loginResponse.getTsig());
                                PreferencesStorageUtil.setStar(LoginActivity.this, loginResponse.getUser_type().equals("star"));
//                                PreferencesStorageUtil.setDiamondCount(LoginActivity.this, loginResponse.get);
                                TIMManager.getInstance().setEnv(Util.ENV_FORMAL);
                                TIMManager.getInstance().init(getApplicationContext());
                                XLApplication.getInstance().refreshRestClient(loginResponse.getAuthentication_token());
                                dismissProgressDialog();
                                initUmeng();
                                toast("登录成功", Toast.LENGTH_SHORT);
                                //todo: 下面的 true 要删除掉
                                if (loginResponse.isNew_user()) {
                                    Intent intent = new Intent(LoginActivity.this, RecommendStarActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    toMainActivity();
                                }
                            }

                            @Override
                            public void failure(RetrofitError error) {
                                toast("登录失败", Toast.LENGTH_SHORT);
                                dismissProgressDialog();
                            }
                        });

            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                dismissProgressDialog();
                throwable.printStackTrace();
                System.out.println("initWeboUser--onError->" + i);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                dismissProgressDialog();
                System.out.println("initWeboUser--onCancel->");
            }
        });
        weibo.showUser(null);
    }



    private void initUmeng(){
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setPushCheck(true);
        mPushAgent.enable();//多调用了一次

        String device_token = PreferencesStorageUtil.getDeviceToken(LoginActivity.this);
        if(!TextUtils.isEmpty(device_token)){
            XLApplication.getInstance().getRestClient().putMobileDevice("Android", device_token, new Callback<NullResponse>() {
                @Override
                public void success(NullResponse nullResponse, Response response) {

                }

                @Override
                public void failure(RetrofitError error) {

                }
            });
        }else{
            mPushAgent.enable(new IUmengRegisterCallback() {
                @Override
                public void onRegistered(String registrationId) {
                    if (!TextUtils.isEmpty(registrationId)) {
                        PreferencesStorageUtil.setDeviceToken(LoginActivity.this, registrationId);//ApBcl59r-3SDm2YCvBci-fA7pvlpqw_fTBPcigRRSIj9
                        XLApplication.getInstance().getRestClient().putMobileDevice("Android",registrationId, new Callback<NullResponse>() {
                            @Override
                            public void success(NullResponse nullResponse, Response response) {
                                RetrofitErrorUtil.handleResponse(LoginActivity.this,response);
                            }

                            @Override
                            public void failure(RetrofitError error) {
                                RetrofitErrorUtil.handleError(LoginActivity.this, error);
                            }
                        });
                    }
                }
            });
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        dismissProgressDialog();
    }

    private void loginWeixin() {
        showProgressDialog();
        Platform wechat = ShareSDK.getPlatform(this,Wechat.NAME);
        if(wechat.isClientValid()){
            wechat.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {
                    dismissProgressDialog();
                    initWexinUser();
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {
                    dismissProgressDialog();
//                showFailureToast();
                }

                @Override
                public void onCancel(Platform platform, int i) {
                    dismissProgressDialog();
//                showFailureToast();
                }
            });
            wechat.authorize();
        }else{
            toast("没有安装微信客户端", Toast.LENGTH_SHORT);
        }


    }

    private void initWexinUser() {
        Platform weixin = ShareSDK.getPlatform(this, Wechat.NAME);
        weixin.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {
                showProgressDialog();

                PlatformDb platDB = platform.getDb();//获取数平台数据DB
                String sex = "male";
                if (!TextUtils.isEmpty(platDB.getUserGender()) ) {
                    if(platDB.getUserGender().equals("f")){
                        sex = "female";
                    }else{
                        sex = "male";
                    }
                }
                XLApplication.getInstance().getRestClient().signIn("weixin", stringObjectHashMap.get("openid").toString(), platDB.getToken(), "",
                        "", stringObjectHashMap.get("headimgurl").toString(), sex, stringObjectHashMap.get("city").toString(), stringObjectHashMap.get("nickname").toString(), "", new Callback<LoginResponse>() {
                            @Override
                            public void success(LoginResponse loginResponse, Response response) {
                                UserUtils.setUserInstance(UserUtils.transLoginRes2User(loginResponse));
                                PreferencesStorageUtil.setUserBean(LoginActivity.this, GsonUtil.toJson(UserUtils.transLoginRes2User(loginResponse)));
                                PreferencesStorageUtil.setToken(LoginActivity.this, loginResponse.getAuthentication_token());
                                PreferencesStorageUtil.setUserid(LoginActivity.this, loginResponse.getId() + "");
                                PreferencesStorageUtil.setTsig(LoginActivity.this, loginResponse.getTsig());
                                PreferencesStorageUtil.setStar(LoginActivity.this, loginResponse.getUser_type().equals("star"));
                                TIMManager.getInstance().setEnv(Util.ENV_FORMAL);
                                TIMManager.getInstance().init(getApplicationContext());
                                XLApplication.getInstance().refreshRestClient(loginResponse.getAuthentication_token());
                                dismissProgressDialog();
                                toast("登录成功", Toast.LENGTH_SHORT);
                                initUmeng();
                                //todo: 下面的 true 要删除掉
                                if (loginResponse.isNew_user()) {
                                    Intent intent = new Intent(LoginActivity.this, RecommendStarActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    toMainActivity();
                                }
                            }

                            @Override
                            public void failure(RetrofitError error) {
                                toast("登录失败", Toast.LENGTH_SHORT);
                                dismissProgressDialog();
                            }
                        });


            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                showProgressDialog();
            }

            @Override
            public void onCancel(Platform platform, int i) {
                showProgressDialog();
            }
        });
        weixin.showUser(null);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }




    private void toMainActivity(){
        startActivity(new Intent(LoginActivity.this, Main2Activity.class));
        finish();
    }


    class MyAdapter extends CycleViewPager.AbstractCircleAdapter {
        private static final int GONGYUE = 1 * 2 * 3 * (4 / 2); // 最多 4 张图片，最少 2
        // 张图片
        private int mOriRealCount = 0;
        private Stack<PagerHolder> mHolders = new Stack<PagerHolder>();
        private SparseArrayCompat<PagerHolder> mAllElementList = new SparseArrayCompat<PagerHolder>(
                4);

        // private HashMap<Integer, PagerHolder> mAllElements = new
        // HashMap<Integer, CycleImagePagerLayout.PagerHolder>(
        // 4);;

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        public void setRealCount(int realCount) {
            mOriRealCount = realCount;
        }

        public int getOffset() {
            return GONGYUE * 1000;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position,
                                   Object object) {
            super.setPrimaryItem(container, position, object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            PagerHolder holder = null;
            if (mHolders.size() > 0) {
                holder = mHolders.pop();
            } else {
                holder = new PagerHolder();
                holder.iv = new ImageView(LoginActivity.this);
//                holder.iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                holder.iv.setAdjustViewBounds(true);
                holder.iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            }
            container.addView(holder.iv);
            holder.realPosition = position % GONGYUE;
            mAllElementList.put(holder.realPosition, holder);
            int[] resouceArr = new int[]{R.drawable.login_page01_moblie, R.drawable.login_page02_moblie,
                R.drawable.login_page03_moblie};
            holder.iv.setImageResource(resouceArr[position % mOriRealCount]);
            return holder;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            PagerHolder holder = (PagerHolder) object;
            container.removeView(holder.iv);
            mAllElementList.remove(holder.realPosition);
            mHolders.push(holder);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == ((PagerHolder) arg1).iv;
        }

    }

    private static class PagerHolder {
        ImageView iv;
        int realPosition;

    }

    class MyPageChangeListener implements MyViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            setPage(position % 3);
        }
    }



}
